import {handlePageChange, back2Home} from '../../router/index'
import Notify from '@vant/weapp/notify/notify';
const $api = require('../../request/index').API;

Page({
  data: {
    active : 1,
    repairs: [
      {
        id: 1,
        user: {
          name: 'xxrl',
          sno: '124',
        },
        description: '显示屏坏了'
      },
      {
        id: 2,
        user: {
          sno: '1242',
        },
        description: '显示屏坏了2asdaadasasfaafasfaafasfasgasfafaafasfasasafas显示屏坏了2sad'
      }
    ],
    curRoom: "1教",
    rooms: [
      "1教", "2教", "3教","1教", "2教", "3教","1教",
    ],

    repair_types: [{text:'软件',value:1},{text:'硬件',value:2},{text:'电源',value:3}],
    repair_desription: '',
    repair_type: 1,
    repair_position: '',

    user_id: 0,
    token: "",
  },
  onLoad(){
    // 请求房间 和 房间对应的报修
    var token , user_id
    try {
      token = wx.getStorageSync('token')
      user_id = wx.getStorageSync('user_id')
      // token 必须存在
      if (!token) {
        Notify({ type: 'warning', message: '网络异常请刷新小程序', onClose: back2Home })
        return
      }
    } catch (e) {
      console.log(e)
      Notify({ type: 'warning', message: '网络异常请刷新小程序', onClose: back2Home })
      return 
    }
    this.setData({token:token, user_id:user_id})
    
    // 加载房间列表
    $api.roomList({page_num:1}, token).then(res => {
      var rooms = res.lists.map((item)=> {
        return item.room
      })

      this.setData({rooms: rooms, curRoom:rooms[0]})
      //加载房间对应的报修
      $api.malfunctionList({room:rooms[0],page_num:1},token).then(res=>{
        console.log(res)
        this.setData({repairs: res.lists})
      })
    }).catch(e => {
      console.log(err)
    }) 

  },
  onRoomChange(event) {
    // 重新请求房间的报修
    $api.malfunctionList({room:this.data.rooms[event.detail],page_num:1},this.data.token).then(res=>{
      this.setData({repairs: res.lists})
    })
    this.setData({curRoom: event.detail})
  },
  onPageChange(event) {
    handlePageChange(event.detail)
    this.setData({active: event.detail})
  },
  onTypeSelectChange(event) {
    this.setData({repair_type: event.detail})
  },

  onSubmit() {
    // 先做校验
    if (!this.data.user_id) {
      Notify({ type: 'warning', message: '提交前请先登录'})
      return
    }
    var {token,repair_desription,repair_type,repair_position, curRoom, user_id} = this.data
    var mal = {description:repair_desription,type:repair_type,room:this.data.rooms[curRoom],position:repair_position, user_id:parseInt(user_id)}
    console.log(mal)
    $api.addMalfunction(mal,token).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'none'
      });
      $api.malfunctionList({room:curRoom,page_num:1},token).then(res=>{
        this.setData({repairs: res.lists,repair_desription:"",repair_type:1,repair_position:""})
      })
    }).catch(e => {
      console.log(e)
    })
  },
});